package com.hong.tomcat;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by John on 2019/1/26.
 * 获取HTTP的请求头所有信息并截取URL地址返回
 * 对浏览器的请求的封装
 */
public class Request extends WrappedRequest{
    /**
     * 请求路径
     */
    private String url;

    /**
     * 请求类型
     */
    private String method;

    /**
     * 应用在tomcat容器中的唯一标识
     */
    private String application;

    /**
     * 通过给定的请求流解析请求信息
     *
     * @param is
     */
    public Request(InputStream is) {
        //try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            /**
             * 读取请求行的数据
             * 请求行类似下面的格式：
             * GET /servlet-study-0.0.1/indexServlet HTTP/1.1
             */
            StringBuilder sb = new StringBuilder();
            String msg = br.readLine();
            String[] request =msg.split(" ");
            sb.append(msg + "\r\n");
            while ((msg = br.readLine()) != null) {
                if (msg.length() == 0) {
                    break;
                }
               sb.append(msg + "\r\n");
            }
            System.out.println("收到请求：" + sb.toString());

            this.method = request[0];
            this.application = request[1].split("/")[1];
            this.url = request[1].substring(application.length() + 1, request[1].length());

            System.out.println("请求类型：" + method);
            System.out.println("请求路径：" + url);
            System.out.println("request end...");
        } catch (Exception e) {
            System.out.println("请求解析异常：" + e.getMessage());
        }
    }

    public String getUrl() {
        return url;
    }

    @Override
    public String getMethod() {
        return method;
    }

    public String getApplication() {
        return application;
    }

}
